package org.opens.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.opens.dao.BaseUserMapper;
import org.opens.dto.PageDTO;
import org.opens.entity.BaseUser;
import org.opens.exception.BusinessException;
import org.opens.service.BaseUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class BaseUserServiceImpl extends ServiceImpl<BaseUserMapper, BaseUser> implements BaseUserService {

    @Autowired
    private BaseUserMapper baseUserMapper;

    @Override
    public BaseUser saveOrUpdateEntityInfo(BaseUser baseUser) {
        if (baseUser == null) {
            throw new BusinessException("操作对象不能为null!");
        }

        if (baseUser.getId() == null) {
            baseUser.setCreateDate(new Date());
            boolean operationFlag = this.save(baseUser);

            if (!operationFlag) {
                throw new BusinessException("保存对象出错!");
            }

            return baseUser;
        } else {
            LambdaUpdateWrapper<BaseUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(BaseUser::getId, baseUser.getId());
            boolean operationFlag = this.update(baseUser, updateWrapper);

            if (!operationFlag) {
                throw new BusinessException("更新对象出错!");
            }

            return this.getById(baseUser.getId());
        }
    }

    @Override
    public BaseUser getOneEntityById(Integer id) {
        LambdaQueryWrapper<BaseUser> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(BaseUser::getId, id);

        // 此处只是为了演示, 实际上有更好用的方法
        return this.getOne(queryWrapper);
    }

    @Override
    public IPage<BaseUser> getPage(BaseUser baseUser, PageDTO pageDTO) {
        Page<BaseUser> page = new Page<>(pageDTO.getPageNumber(), pageDTO.getSize());
        return this.page(page);
    }

    @Override
    public boolean batchUpdate(List<Integer> ids) {
        LambdaUpdateWrapper<BaseUser> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.in(BaseUser::getId, ids);

        BaseUser baseUserUpdateObj = new BaseUser();
        baseUserUpdateObj.setAge(33);

        return this.update(baseUserUpdateObj, updateWrapper);
    }

    @Override
    public IPage<BaseUser> getBaseUserList(BaseUser baseUser, PageDTO pageDTO) {
        // 不传入page对象会报错: 空指针异常
        return this.baseUserMapper.getBaseUserList(null, baseUser);
    }
}
